<template>
	<view class="mt-16">
		<view class="logo-content align-center justify-center flex">
			<image style="width: 400rpx;height: 100rpx;" :src="globalConfig.appInfo.loginLOGO" mode="widthFix">
			</image>

		</view>
		<view class="mt-4">
			<up-card :border="false" :foot-border-top="false" :head-border-bottom="false">
				<template #body>
					<view class="" slot="body">
						<up-form :model="loginForm" ref="formRef" labelWidth="60px" labelAlign="center"
							:rules="formRules">
							<up-form-item prop="username">
								<up-input v-model="loginForm.username" placeholder="请输入用户姓名" type="text"
									prefixIcon="account" shape="circle" fontSize="18px"
									prefixIconStyle="color:#205f66;font-size:20px;margin-right:40px" />
							</up-form-item>
							<up-form-item prop="password">
								<up-input v-model="loginForm.password" placeholder="请输入密码" type="password"
									prefixIcon="lock" shape="circle" fontSize="18px"
									prefixIconStyle="color:#205f66;font-size:20px;margin-right:40px" />
							</up-form-item>

						</up-form>
						<Verify @success="pwdLogin" :mode="'pop'" :captchaType="'blockPuzzle'"
							:imgSize="{ width: '330px', height: '155px' }" ref="verify"></Verify>
					</view>
				</template>
				<template #foot>
					<up-button shape="circle" type="primary" @click="handleLogin">登录</up-button>
					<!-- <view class="m-4 text-center">
						<text class="text-grey1">登录即代表同意</text>
						<text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
						<text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
					</view> -->
					<view class="agreement px-4 py-8">
						<checkbox class="checkbox" :checked="agreed" @click="toggleAgreement" />
						<text class="agreement-text">我已认真阅读留言须知。查看</text>
						<text class="link" @click="handleUserAgrement">《用户服务协议》</text>
						<text class="agreement-text">及</text>
						<text class="link" @click="handlePrivacy">《个人信息保护政策》</text>
					</view>
				</template>
			</up-card>
		</view>
	</view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue';
import Verify from "@/components/verifition/index.vue";
import { useUserStore } from '@/store/modules/user'
import { useDictStoreWithOut } from '@/store/modules/dict'


const store = useUserStore(); // 获取 Vuex store
const dictStore = useDictStoreWithOut()
const globalConfig = (getApp() as any).globalData.config;
const verify = ref();
const captchaEnabled = ref(true);

const redirect = ref('')
const agreed = ref(false)
const formRef = ref()
const loginForm = ref({
	username: "",
	password: "",
	// password: "",
	captchaVerification: ""
});
const formRules = {
	username: [{
		required: true,
		message: '请输入用户名',
		trigger: ['blur', 'change'],

	},
	{
		validator: (value: any) => {
			if (value) {
				return Promise.resolve();
			} else {
				return Promise.reject('用户名不能为空');
			}
		},
	}],
	password: [{
		required: true,
		message: '请输入密码',
		trigger: ['blur', 'change'],
	},
	// 正则判断为字母或数字
	// {
	// 	pattern: /^[0-9a-zA-Z]*$/g,
	// 	// 正则检验前先将值转为字符串
	// 	transform(value:any) {
	// 		return String(value);
	// 	},
	// 	message: '只能包含字母或数字'
	// },
	// 6-8个字符之间的判断
	{
		min: 5,
		max: 12,
		message: '长度在5-12个字符之间'
	},
	{
		validator: (value: any) => {
			if (value) {
				return Promise.resolve();
			} else {
				return Promise.reject('密码不能为空');
			}
		},
	}],
}

const handlePrivacy = () => {
	let site = globalConfig.appInfo.agreements[0];
	uni.navigateTo({ url: `/pages/common/webview/index?title=${site.title}&url=${site.url}` });
};

const handleUserAgrement = () => {
	let site = globalConfig.appInfo.agreements[1];
	uni.navigateTo({ url: `/pages/common/webview/index?title=${site.title}&url=${site.url}` });
};
const toggleAgreement = () => {
	console.log('aaa');

	agreed.value = !agreed.value
}
const handleLogin = async () => {
	if (!agreed.value) {
		uni.showToast({
			title: '请先阅读并同意协议',
			icon: 'none',
		})
		return
	}
	// 校验表单
	if (!formRef.value) return
	const valid = await formRef.value.validate();
	console.log('valid', valid);
	// const { valid, errors } = await formRef.value.validate();
	if (!valid) {
		// console.log('表单校验未通过:', errors);
		return; // ✅ 校验失败，终止后续代码
	}
	// await pwdLogin({})
	if (captchaEnabled.value && verify.value) {
		verify.value.show();
	} else {
		console.log('没进来');
		await pwdLogin({});
	}
};
const pwdLogin = async (captchaParams: any) => {
	uni.showLoading({ title: '登录中，请耐心等待...' });
	loginForm.value.captchaVerification = captchaParams.captchaVerification;
	try {
		await store.Login(loginForm.value);
		// console.log('res', res);
		loginSuccess();
	} finally {
		uni.hideLoading();
	}
};
const loginSuccess = async () => {
	await store.setUserInfoAction();
	await dictStore.setDictMap()
	if (redirect.value) {
		// 登录成功后回到原页面
		uni.reLaunch({ url: redirect.value })
	} else {
		// 默认首页
		uni.reLaunch({ url: '/pages/index/index' })
	}
};
onLoad((options: any) => {
	redirect.value = decodeURIComponent(options.redirect || '') // 401 跳转时传过来的
	console.log('redirect.value', redirect.value);

})
</script>

<style scoped>
.agreement {
	flex-direction: row;
	align-items: center;
	flex-wrap: wrap;
}

.checkbox {
	transform: scale(0.8);
	margin-right: 8rpx;
	margin-bottom: 12rpx;
}

.agreement-text {
	font-size: 30rpx;
	color: #999;
}

.link {
	font-size: 30rpx;
	color: #000;
	text-decoration: underline;
	margin: 0 8rpx;
}

.disabled {
	opacity: 0.6;
	background: #ccc;
}
</style>